﻿/* JSON字符串转换类
 */

/* 1、未完成全部类型
 * 2、不同类型的重载
 * 3、单元测试
 */
namespace LSLib.StringEx
{
    using System.Collections.Generic;

    /// <summary>JSON数据转换类
    /// </summary>
    public static class ConvJSON
    {
        /* JSON 参考数据 : Item
        { "firstName":"John" , "lastName":"Doe" }
        */
        public static string ConvItem(Dictionary<string, string> dictData)
        {
            string result = string.Empty;
            foreach (KeyValuePair<string, string> next in dictData)
            {
                result += string.Format("\"{0}\":\"{1}\",", next.Key, next.Value);
            }
            result = result.Substring(0, result.LastIndexOf(","));
            result = "{" + result + "}";
            return result;
        }

        /* JSON 参考数据 : Array
        {
        "employees": [
        { "firstName":"John" , "lastName":"Doe" },
        { "firstName":"Anna" , "lastName":"Smith" },
        { "firstName":"Peter" , "lastName":"Jones" }
        ]
        }
        */
        public static string ConvArray(string name, params Dictionary<string, string>[] Datas)
        {
            string result = string.Empty;
            string temp = string.Empty;
            foreach (Dictionary<string, string> next in Datas)
            {
                temp += string.Format("{0},\r\n", ConvItem(next));
            }
            temp = temp.Substring(0, temp.LastIndexOf(","));
            result = string.Format("{\r\n\"{0}\": [\r\n{1}\r\n]\r\n}", name, temp);
            return result;
        }
    }
}
